<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------


namespace TpAmis\build\controller;


use app\BaseController;
use think\App;
use think\facade\Env;
use TpAmis\Traits;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\facade\Cache;

/**
 * @ControllerAnnotation(title="amis后台管理")
 */
class AmisAdminController extends BaseController
{

    use Traits\JumpTrait;
    use Traits\ExportTrait;
    use Traits\UploadTrait;
    use Traits\RequestTrait;
    use Traits\ElementTrait;
    use Traits\QueryPathTrait;
    use Traits\FileManagerTrait;
    use Traits\CheckActionTrait;
    use Traits\IconifyPickerTrait;

    /** @var   $queryPath 路径 */
    protected $queryPath;
    /**
     * 当前模型
     * @Model
     * @var object
     */
    protected $model;

    /**
     * 字段排序
     * @var array
     */
    protected $sort = [
        'id' => 'desc',
    ];


    /**
     * 下拉选择条件
     * @var array
     */
    protected $selectWhere = [];

    /**
     * 是否关联查询
     * @var bool
     */
    protected $relationSearch = false;

    /**
     * 模板布局, false取消
     * @var string|bool
     */
    protected $layout = 'amis/index/index';

    /**
     * 是否为演示环境
     * @var bool
     */
    protected $isDemo = false;

    /** @var string|mixed $adminPrefix 路由前缀 */
    protected $adminPrefix;
    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();

        $this->adminPrefix = config('admin.route.prefix');

    }

    /**
     * 初始化方法
     */
    protected function initialize()
    {

        $this->layout && $this->app->view->engine()->layout($this->layout);

    }



    protected function cacheMethodWhere($where)
    {
        Cache::store('redis')->hset('product.listing.search', session('admin.id'), json_encode($where));
    }

    /**
     * 模板变量赋值
     * @param string|array $name 模板变量
     * @param mixed $value 变量值
     * @return mixed
     */
    public function assign($name, $value = null)
    {
        return $this->app->view->assign($name, $value);
    }


    /**
     * 解析和获取模板内容 用于输出
     * @param array $vars
     * @return mixed
     */
    public function fetch($vars = [])
    {

        $assign['amisJSON'] = amis()->Page()->className('m:overflow-auto pb-48')->body($vars);
        $assign['extend_css_list'] = Env::get('extend_css_list');
        $assign['extend_js_list'] = Env::get('extend_js_list');
        
        return $this->app->view->fetch($this->layout, $assign);
    }

    /**
     * 重写验证规则
     * @param array $data
     * @param array|string $validate
     * @param array $message
     * @param bool $batch
     * @return array|bool|string|true
     */
    public function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        try {
            parent::validate($data, $validate, $message, $batch);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        return true;
    }

    public function form()
    {
        return $this->baseForm();
    }

    /**
     * 递归处理布尔值
     * @param mixed $data
     * @return mixed
     */
    protected function convertBooleansToNumbers(&$data)
    {
        if (is_array($data)) {
            foreach ($data as &$value) {
                $this->convertBooleansToNumbers($value);
            }
        } elseif (is_object($data)) {
            foreach ($data as &$value) {
                $this->convertBooleansToNumbers($value);
            }
        } elseif (is_bool($data)) {
            $data = $data ? 1 : 0;
        }
        return $data;
    }

    /**
     * @NodeAnotation(title="快速更新")
     */
    public function modify()
    {
        // 获取原始的 JSON 数据
        $jsonData = file_get_contents('php://input');

        // 解析 JSON 数据
        $rows = json_decode($jsonData, true);

        // 调用自定义的函数处理布尔值
        if (is_array($rows)) {
            $this->convertBooleansToNumbers($rows);
        }

        // 继续处理 $rows
        $rows = $this->convertBooleansToNumbers($rows);

        if (isset($rows['rowsDiff'])) {
            $ids = explode(',', $rows['ids']);

            // 遍历每个记录进行验证和更新
            foreach ($rows['rowsDiff'] as $index => $row) {
                // 更新记录
                try {
                    $data = $this->model->where('id', $ids[$index])->find();
                    unset($row['create_time']);
                    unset($row['update_time']);
                    $data->save($row);
                } catch (\Exception $e) {
                    $this->error("第" . ($index + 1) . "个记录更新失败: " . $e->getMessage());
                }
            }
        } else if (isset($rows['id'])) {
            $data = $this->model->where('id', $rows['id'])->find();
            unset($rows['create_time']);
            unset($rows['update_time']);
            $data->save($rows);
        }


        $this->success();
    }
}
